<?php
class Project extends CI_Controller {

function __construct()
    {
        parent::__construct();
        
        $this->load->model('project_model');
        $this->load->helper(array('form','url'));
        $this->load->library('form_validation');
    }
	function index(){
        $this->load->view('ProjectsList');
    } 
	function getProjects(){
		$page = $this->input->post('page');
		$limit = $this->input->post('rows');
		$sidx = $this->input->post('sidx');
		$sord = $this->input->post('sord');
		
		if(!$sidx) $sidx =1;
		
		$count = $this->project_model->getProjectsCount();

		if( $count > 0 ) {
			$total_pages = ceil($count/$limit);
		} else {
			$total_pages = 0;
		}
		if ($page > $total_pages) $page=$total_pages;
		$start = $limit*$page - $limit; // do not put $limit*($page - 1)
		
		$responce->page = $page;
		$responce->total = $total_pages;
		$responce->records = $count;
		
		$projects = $this->project_model->getProjects($sidx, $sord, $start , $limit); 
		
		for($i=0; $i< sizeof($projects); $i++) {
			$responce->rows[$i]['id'] = $projects[$i]['id'];
			$responce->rows[$i]['cell'] = array($projects[$i]['id'], 
												$projects[$i]['name'], 
												$projects[$i]['description'],
												$projects[$i]['start_date']);
		}
     	
		echo json_encode($responce);
	}
	function newProject(){
		$this->load->view('NewProject');
	}
	function create(){
		$this->load->library('form_validation');
		//Check incoming variables
		$this->form_validation->set_rules('name','Name','required|trim|max_length[50]|xss_clean');         
		if ($this->form_validation->run() == false) {
			$this->load->view('NewProject');			
		} else {
			$name=$this->input->post('name');
			$desc=$this->input->post('description');
			$this->project_model->newProj($name,$desc);
			$this->session->set_flashdata('validation',TRUE);
			$this->load->view('ProjectsList');
		}		
	}
	function delete(){
		$proj = $_POST['idProj'];
		$this->project_model->delete($proj);
		$this->load->view('ProjectsList');
	}
	function editProj(){
		$proj = $_POST['idProj'];
		$var=  $this->project_model->getProj($proj);
		$data['name'] = $var[0]['name'];
		$data['description'] = $var[0]['description'];
        $data['id'] = $var[0]['id'];
		$this->load->view('EditProject',$data);
	}
	function update(){
		$id = $_POST['id'];
		$name=$this->input->post('name');
		$desc=$this->input->post('description');
		$this->project_model->update($id,$name,$desc);
		$this->load->view('ProjectsList');
	}
}

?>